package com.ocom.app.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ocom.common.entity.base.EntityBase;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
  @Override
  public void insertFill(MetaObject metaObject) {

    if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof EntityBase) {
      EntityBase baseDO = (EntityBase) metaObject.getOriginalObject();

      Date current = new Date();
      // 创建时间为空，则以当前时间为插入时间
      if (Objects.isNull(baseDO.getCreateTime())) {
        baseDO.setCreateTime(current);
      }
      // 更新时间为空，则以当前时间为更新时间
      if (Objects.isNull(baseDO.getUpdateTime())) {
        baseDO.setUpdateTime(current);
      }


    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof EntityBase) {
      EntityBase baseDO = (EntityBase) metaObject.getOriginalObject();

      Date current = new Date();
      // 更新时间为空，则以当前时间为更新时间
      if (Objects.isNull(baseDO.getUpdateTime())) {
        baseDO.setUpdateTime(current);
      }

    }
  }
}
